package com.neu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.neu.constant.PlanStatusEnum;
import com.neu.constant.ResultCodeEnum;
import com.neu.mapper.PlanMapper;
import com.neu.pojo.Article;
import com.neu.pojo.Cooperator;
import com.neu.pojo.Plan;
import com.neu.service.PlanService;
import com.neu.utils.ExcelListener;
import com.neu.utils.Result;
import com.neu.vo.PlanVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class PlanServiceImpl implements PlanService {

    @Resource
    private PlanMapper planMapper;

    @Override
    public int add(PlanVO planVO) {
        planMapper.deletePlanGroup(planVO.getProjectId());
        return planMapper.insertPlanGroup(planVO.getList());
    }

    @Override
    public List<Plan> list(int projectId) {
        return planMapper.queryPlanList(projectId);
    }

    @Override
    public int add(Plan plan) {
        return planMapper.insertPlan(plan);
    }

    @Override
    public int delete(Plan plan) {
        return planMapper.deletePlan(plan.getId());
    }

    @Override
    public int update(Plan plan) {
        return planMapper.updatePlan(plan);
    }

    @Override
    public Object batchInsertPlan(MultipartFile file, int provinceId) throws IOException {
        ExcelReader excelReader = null;
        InputStream in = null;
        ExcelListener listener = new ExcelListener();
        try {
            in=file.getInputStream();
            excelReader = EasyExcel.read(in, Plan.class,listener).build();
            excelReader.read(EasyExcel.readSheet(0).build());
            List<Plan> planList=new ArrayList<Plan>();
            for(Object o:listener.getData()){
                Plan p=(Plan) o;
                if(PlanStatusEnum.of(p.getStatus())==PlanStatusEnum.UNKNOWN){
                    return Result.error(ResultCodeEnum.EXCEL_PLAN_STATUS_ERROR);
                }
                if(Objects.isNull(p.getSdate())||Objects.isNull(p.getEdate())){
                    return Result.error(ResultCodeEnum.EXCEL_PLAN_DATE_ERROR);
                }
                p.setProjectId(provinceId);
                planList.add(p);
            }
            for(Plan p:planList){
                planMapper.insertPlan(p);
            }
        } catch (Exception e) {
            log.error("导入失败",e);
            return Result.error(ResultCodeEnum.EXCEL_ERROR);
        } finally {
            in.close();
            // 这里一定别忘记关闭，读的时候会创建临时文件，到时磁盘会崩
            if (excelReader != null) {
                excelReader.finish();
            }
        }
        return 0;
    }
}
